package com.lgs7907.simplestockinfo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Date;
import java.text.SimpleDateFormat;

import android.os.AsyncTask;
import android.util.Log;

//FileDownloaderTask task = new FileDownloaderTask(new FileDownloaderTask.ICallback() {
//	@Override
//	public void afterPost(File file) {
//		//TODO;
//	}
//});
public class FileDownloaderTask extends AsyncTask<String, Void, File> {
	private ICallback callback;

	public FileDownloaderTask(ICallback iCallback) {
		this.callback = iCallback;
	}

	@Override
	protected File doInBackground(String... params) {
		// 实际的下载线程，内部其实是concurrent线程，所以不会阻塞
		return downloadFile(params[0]);
	}

	public File downloadFile(String url) {
		if (url.length() < 10) {
			Log.e("mhs", "download file url wrong = " + url);
			return null;
		}

		URL myFileUrl = null;
		try {
			myFileUrl = new URL(url);
		} catch (MalformedURLException e) {
			Log.e("mhs", "download file get url err: " + e.getMessage());
			// e.printStackTrace();
			return null;
		}
		File temp = null;
		InputStream is = null;
		OutputStream os = null;
		try {
			HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
			conn.setDoInput(true);
			conn.connect();
			is = conn.getInputStream();

			SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
			Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
			String strFile = formatter.format(curDate);

			temp = File.createTempFile(strFile, ".temp");
			temp.deleteOnExit();// 在程序退出时删除临时文件

			// 向临时文件中写入内容
			os = new FileOutputStream(temp);
			byte buffer[] = new byte[1024];
			while (is.read(buffer) != -1) {
				os.write(buffer);
			}
			os.flush();

		} catch (IOException e) {
			Log.e("FileDownloaderTask", "远程文件不存在: " + e.getMessage());
			// e.printStackTrace();
		} finally {
			try {
				if (is != null)
					is.close();
				if (os != null)
					os.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return temp;
	}

	@Override
	protected void onPostExecute(File file) { // 下载完后执行的
		if (isCancelled()) {
			file = null;
		}
		callback.afterPost(file);
	}

	public interface ICallback {
		public void afterPost(File bitmap);
	}
}